<template>
	<view>
		<view class="wfc mlr shadow-1 bb p-10 br-6" style="width: 90%;margin-top: 6vh;">
			<image show-menu-by-longpress :src="placardImg" class="br-6" style="width: 100%;" mode="widthFix"></image>
		</view>
		<view @click="saveAlbum" class="box-save wfc mlr">
			<text>保存到相册</text>
		</view>

		<view class="" style="text-align: center;"></view>

		<!-- 绘制海报 -->
		<l-painter v-if="isCanvasToTempFilePath" isCanvasToTempFilePath @success="painterSuccess" hidden
			css="width: 750rpx;">
			<l-painter-view
				css="width: 750rpx;height: 1200rpx;background-image: url('https://yjgs.jsonbug.com/test/huiyuan.png');position: relative;">

				<!-- 公司名称 -->
				<l-painter-text :text="company_name"
					css="text-align: center;margin-left: 10rpx;width: 78%;line-clamp:2;position: absolute;font-size: 32rpx;color: #282C35;font-weight: bold;left: 50%;transform: translateX(-50%);top:43%" />
				<!-- end -->

				<!-- 证书编号 -->
				<l-painter-text :text="'证书编号：'+company_code"
					css="position: absolute;font-size: 26rpx;color: #282C35;left: 50%;transform: translateX(-50%);top:51.6%" />
				<!-- end -->

				<!-- 有效期 -->
				<l-painter-text :text="'有效期限：'+valid_time"
					css="position: absolute;font-size: 26rpx;color: #282C35;left: 50%;transform: translateX(-50%);top:56%" />
				<!-- end -->

				<!-- 分销码 -->
				<l-painter-image :src="shareCode"
					css="height: 200rpx;width: 200rpx;object-fit: cover;position: absolute;left: 50%;transform: translateX(-50%);top: 61%;" />
				<!-- end -->

			</l-painter-view>
		</l-painter>
		<!-- end -->

	</view>
</template>

<script>
	import Cache from '@/utils/cache.js';
	import {
		USER_INFO
	} from '@/config/cache.js';
	import {
		createQRCode
	} from '@/api/extend.js';
	import lPainter from '@/pages/extend/components/lime-painter/components/l-painter/l-painter.vue';
	import lPainterView from '@/pages/extend/components/lime-painter/components/l-painter-view/l-painter-view.vue';
	import lPainterText from '@/pages/extend/components/lime-painter/components/l-painter-text/l-painter-text.vue';
	import lPainterImage from '@/pages/extend/components/lime-painter/components/l-painter-image/l-painter-image.vue';
	export default {
		components: {
			lPainter,
			lPainterView,
			lPainterText,
			lPainterImage,
		},
		data() {
			return {
				myCard: {},
				valid_time: '',
				company_name: '',
				company_code: '',
				isCanvasToTempFilePath: false,
				placardImg: '',
				shareCode: ''
			}
		},
		onLoad() {
			uni.showLoading({
				title: '生成中...',
			})
			let user = Cache.get(USER_INFO, true);
			this.myCard = uni.getStorageSync('userCardInfo');
			this.company_name = this.myCard.position.company_name || '未知信息'
			this.company_code = 'YJGS0' + this.myCard.uid

			if (user) {
				let svip_endtime = this.$timer.formatTime(user.svip_endtime);
				this.valid_time =
					`${this.$timer.formatTime(this.addOrJOneYear(svip_endtime,'reduce'),'yyyy年mm月dd日')} 至 ${this.$timer.formatTime(svip_endtime,'yyyy年mm月dd日')}`
			} else {
				let create_time = this.$timer.formatTime(this.myCard.create_time);
				this.valid_time =
					`${this.$timer.formatTime(create_time,'yyyy年mm月dd日')} 至 ${this.$timer.formatTime(this.addOrJOneYear(create_time,'add'),'yyyy年mm月dd日')}`
			}
			
			this.getcreateQRCode();

		},
		methods: {
			downloadBase64ImageToAlbum(base64Data) {
				// 提取 Base64 内容
				const base64Content = base64Data.split(',')[1];

				// 将 Base64 字符串转换为 ArrayBuffer
				const buffer = wx.base64ToArrayBuffer(base64Content);

				// 创建临时文件路径
				const tempFilePath = `${wx.env.USER_DATA_PATH}/temp_image.png`;

				// 使用 wx.getFileSystemManager() 保存文件
				const fs = wx.getFileSystemManager();

				fs.writeFile({
					filePath: tempFilePath,
					data: buffer,
					encoding: 'binary',
					success: function() {
						// 保存到相册
						wx.saveImageToPhotosAlbum({
							filePath: tempFilePath,
							success: function() {
								wx.showToast({
									title: '保存成功',
									icon: 'success'
								});
							},
							fail: function(err) {}
						});
					},
					fail: function(err) {
						console.error('文件保存失败:', err);
						wx.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}
				});
			},
			saveAlbum() {

				if (!this.placardImg) {
					uni.showToast({
						title: '等待证书生成...',
						icon: 'none'
					})
					return;
				}

				if (!this.myCard.position.company_name) {
					uni.showToast({
						title: '检测到你的证书信息不完整，请删除小程序后重新登录生成！',
						icon: 'none',
						duration: 4000
					})
					uni.removeStorageSync('userCardInfo');
					uni.navigateBack();
				}

				this.downloadBase64ImageToAlbum(this.placardImg);

			},
			addOrJOneYear(dateString, type) {
				const date = new Date(dateString);
				if (type == 'add') {
					date.setFullYear(date.getFullYear() + 1);
				} else {
					date.setFullYear(date.getFullYear() - 1);
				}
				return date.toISOString().slice(0, 19).replace('T', ' ');
			},
			getcreateQRCode() {

				let data = uni.getStorageSync('user_spread_code');
				if (data) {
					this.shareCode = data
					this.isCanvasToTempFilePath = true;
					return;
				}

				uni.showLoading({
					title: '获取分销码中...'
				})
				createQRCode().then(res => {
					uni.showLoading({
						title: '授权中...'
					})
					if (res.status == 200) {
						uni.setStorageSync('user_spread_code', res.data)
						this.shareCode = res.data;
						this.isCanvasToTempFilePath = true;
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none',
							duration: 4000
						})
					}

				})
			},

			painterSuccess(e) {
				this.placardImg = e;
				setTimeout(() => {
					uni.hideLoading();
				}, 300)

				if (!this.myCard.position.company_name) {
					uni.showToast({
						title: '检测到你的证书信息不完整，请删除小程序后重新登录生成！',
						icon: 'none',
						duration: 4000
					})
					uni.removeStorageSync('userCardInfo');
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.box-save:active {
		opacity: .5;
	}

	.box-save {
		margin-top: 20rpx;
		border-radius: 6rpx;
		text-align: center;
		line-height: 70rpx;
		width: 300rpx;
		height: 70rpx;
		background-color: #00009E;
		color: white;
	}
</style>